﻿using Antlr4.Runtime.Tree;
using System;
using System.Collections.Generic;
using System.Text;
using static ttparser.ttlangParser;

namespace TT.Compiler.Node
{
    static class NodeHelper
    {
        public static string ConvID(ITerminalNode id)
        {
            return id.GetText();
        }


        public static Define.Modifier ConvModifier(ModifierContext mod)
        {
            if (mod == null || mod.children == null || mod.children.Count == 0)
                return Define.Modifier.None;
            else
            {
                var txt = mod.GetText();
                if (txt == "export")
                    return Define.Modifier.Export;
                else if (txt == "const")
                    return Define.Modifier.Const;
                else if (txt == "share")
                    return Define.Modifier.Share;
                else
                    throw new Exception("unknown modifier");
            }
        }
        public static bool TryConvInt(NumberContext number, ref UInt64 v)
        {
            if (number == null)
                return false;
            var txt = number.GetText();
            if (txt.IndexOf("0x") == 0)
            {
                return UInt64.TryParse(txt.Substring(2), System.Globalization.NumberStyles.HexNumber, null, out v);
            }
            else if (txt.IndexOf("0b") == 0)
            {
                try
                {
                    v = Convert.ToUInt64(txt.Substring(2), 2);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                return UInt64.TryParse(txt, out v);
            }

        }
    }
}
